import cv2
import numpy as np


def clahe_dehaze(img, clip_limit=2.0, tile_grid_size=(8, 8)):
    # 转换为YCrCb色彩空间
    ycrcb = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
    # 分离通道
    channels = list(cv2.split(ycrcb))
    # 创建CLAHE对象
    clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=tile_grid_size)
    # 对Y通道进行CLAHE
    channels[0] = clahe.apply(channels[0])
    # 合并通道
    ycrcb = cv2.merge(channels)
    # 转换回BGR色彩空间
    result = cv2.cvtColor(ycrcb, cv2.COLOR_YCrCb2BGR)
    return result


# 读取图像
im = cv2.imread('images_origin/U.png')
if im is None:
    raise FileNotFoundError("The image file was not found. Please check the path.")

# 使用CLAHE进行图像去雾
eq = clahe_dehaze(im)

# 显示原始图像和处理后的图像
cv2.imshow('Original Image', im)
cv2.imshow('CLAHE Dehazed Image', eq)
cv2.waitKey(0)
cv2.destroyAllWindows()

# 保存处理后的图像
cv2.imwrite('img_clahe_dehazed.png', eq)
